<script setup lang="ts">
import { ref, watch } from "vue";

import { UploadFilled } from "@element-plus/icons-vue";
import type { FormItemProps } from "../utils/types.js";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { message } from "@/utils/message";

const props = defineProps<FormItemProps>();
const emit = defineEmits(["success"]);

const formRef = ref();
const form = ref<{
  Id?: number;
  UserId?: number;
  UserName?: string;
  BindType?: string;
  MainBindCode?: string;
  SlaveBindCode?: string;
  ThreeBindCode?: string;
  Status?: number;
  TenantId?: number;
  TenantName?: string;
  DealerId?: number;
  DealerName?: string;
  Avatar?: string;
  [key: string]: any;
}>({});

// 上传图片相关
const imageUrl = ref("");
const uploadUrl = changeHttpLink("index.php/upload/image");
const uploadHeaders = ref({
  Authorization: localStorage.getItem("token") || ""
});

const handleAvatarSuccess = (response: any, uploadFile: any) => {
  if (response.status === "success") {
    imageUrl.value = response.data.url;
    form.value.Avatar = response.data.url;
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error("图片上传失败");
  }
};

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

// 表单规则
const rules = {
  UserId: [{ required: true, message: "请输入用户ID", trigger: "blur" }],
  UserName: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  BindType: [{ required: true, message: "请选择绑定类型", trigger: "blur" }],
  MainBindCode: [
    { required: true, message: "请输入主关联码", trigger: "blur" }
  ],
  Status: [{ required: true, message: "请选择状态", trigger: "blur" }]
};

watch(
  () => props.form,
  val => {
    form.value = { ...val };
    if (val?.Avatar) {
      imageUrl.value = val.Avatar;
    }
  },
  { immediate: true }
);

function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const params = { ...form.value };
      http
        .post(
          changeHttpLink(
            props.type === "新增"
              ? "/api/loginBind/add"
              : "/api/loginBind/update"
          ),
          {
            data: params
          }
        )
        .then((res: any) => {
          if (res.Success) {
            message(`${props.type}登录绑定成功`, { type: "success" });
            emit("success");
          } else {
            message(res.Message, { type: "error" });
          }
        })
        .catch(err => {
          message(err.message, { type: "error" });
        });
    }
  });
}
</script>

<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="120px"
    class="w-full"
  >
    <el-form-item label="用户ID" prop="UserId">
      <el-input
        v-model="form.UserId"
        placeholder="请输入用户ID"
        type="number"
      />
    </el-form-item>
    <el-form-item label="用户名称" prop="UserName">
      <el-input v-model="form.UserName" placeholder="请输入用户名称" />
    </el-form-item>
    <el-form-item label="绑定类型" prop="BindType">
      <el-select v-model="form.BindType" placeholder="请选择绑定类型">
        <el-option label="账号密码" value="account" />
        <el-option label="SIM卡关联" value="sim" />
      </el-select>
    </el-form-item>
    <el-form-item label="主关联码" prop="MainBindCode">
      <el-input v-model="form.MainBindCode" placeholder="请输入主关联码" />
    </el-form-item>
    <el-form-item label="从关联码" prop="SlaveBindCode">
      <el-input v-model="form.SlaveBindCode" placeholder="请输入从关联码" />
    </el-form-item>
    <el-form-item label="三关联码" prop="ThreeBindCode">
      <el-input v-model="form.ThreeBindCode" placeholder="请输入三关联码" />
    </el-form-item>
    <el-form-item label="状态" prop="Status">
      <el-select v-model="form.Status" placeholder="请选择状态">
        <el-option label="正常" value="1" />
        <el-option label="异常" value="0" />
      </el-select>
    </el-form-item>
    <el-form-item label="租户ID" prop="TenantId">
      <el-input
        v-model="form.TenantId"
        placeholder="请输入租户ID"
        type="number"
      />
    </el-form-item>
    <el-form-item label="租户名称" prop="TenantName">
      <el-input v-model="form.TenantName" placeholder="请输入租户名称" />
    </el-form-item>
    <el-form-item label="经销商ID" prop="DealerId">
      <el-input
        v-model="form.DealerId"
        placeholder="请输入经销商ID"
        type="number"
      />
    </el-form-item>
    <el-form-item label="经销商名称" prop="DealerName">
      <el-input v-model="form.DealerName" placeholder="请输入经销商名称" />
    </el-form-item>
    <el-form-item label="用户头像">
      <el-upload
        class="avatar-uploader"
        action="{{ uploadUrl }}"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <div v-else class="avatar-uploader-icon">
          <UploadFilled class="el-icon--upload" />
        </div>
      </el-upload>
      <div class="text-xs text-gray-500 mt-1">
        支持JPG、PNG格式，大小不超过2MB
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm"> 确定 </el-button>
      <el-button @click="formRef.value.resetFields()"> 重置 </el-button>
    </el-form-item>
  </el-form>
</template>
<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c8c8c;
  text-align: center;
  cursor: pointer;
  background-color: #f5f5f5;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}
</style>
